﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BBPA.Admin.Store.Orders
{
    public partial class Form : FormPage
    {
        BLL.Orders bll = new BLL.Orders();
        Model.Orders model = new Model.Orders();
        //
        BLL.V_Orders_Goods bllV_Orders_Goods = new BLL.V_Orders_Goods();
        BLL.Orders_Goods bllOrders_Goods = new BLL.Orders_Goods();
        //
        protected static decimal ExpectPriceSum = 0,needMoreMoney=0;
        //
        Model.Store CurrentStore = new Model.Store();
        protected void Page_Load(object sender, EventArgs e)
        {
            CurrentStore = Security.GetCurrentStore();
            //订单ID
            LoadOrder();
        }


        private void LoadOrder()
        {
            BLL.Orders bllOrders = new BLL.Orders();
            List<Model.Orders> listModelOrders_WaitMoney = bllOrders.GetModelList("StoreID=" + CurrentStore.id + " and State<=" + (int)EnumHelper.OrdersState.WaitMoney);
            if (listModelOrders_WaitMoney.Count == 0)
            {
                Model.Orders modelOrder_new = new Model.Orders();
                modelOrder_new.StoreID = CurrentStore.id;
                modelOrder_new.Number = DateTime.Now.ToString("yyyyMMddHHmm") + CurrentStore.Number;
                modelOrder_new.State = (int)EnumHelper.OrdersState.NoGoods;
                Master.id = bllOrders.Add(modelOrder_new);
            }
            else Master.id = listModelOrders_WaitMoney[0].id;
        }
        /// <summary>
        /// 初始化本页Model
        /// </summary>
        public override void Page_Load_DefaultModel() { model = bll.GetModel(Master.id); }
        /// <summary>
        /// 初始化表单
        /// </summary>
        public override void Form_Default()
        {
            Master.HideSubmit();
        }
        /// <summary>
        /// 绑定表单数据【修改时用】
        /// </summary>
        public override void Form_Bind()
        {
            lb_SendDate.Text = DataTypePlus.WeekDay2Date(CurrentStore.BuyDay).ToShortDateString();
            //lb_SendDate.Text =model.BuyDate .ToShortDateString();
            rp_Goods_Bing();

        }
        /// <summary>
        /// 提交
        /// </summary>
        public override void Form_Submit()
        {
            #region old code
            //string Name = PageValidate.SqlTextClear(DataTypePlus.requestString(tb_Name.Text));

            //if (
            //    PageValidate.noEmpty(Name, "[品牌名称]必须填写") &&
            //    Master.noChongfu("Name='" + Name + "'", "[品牌名称]重复")
            //    )
            //{
            //   // model.Name = Name;
            //    if (Master.formState == EnumHelper.FormState.add)Master.id= bll.Add(model);
            //    else bll.Update(model);
            //    BLL.User_Operate_Log.Add(Security.GetCurrentUserID(), EnumHelper.TableName.Goods_BuyPrice_Log, Master.id, Master.formState == EnumHelper.FormState.add ? EnumHelper.OperateType.Add : EnumHelper.OperateType.Update, "");
            //    Master.SubmitOK();

            //}





            //string Orders_GoodsIDStr = "";
            //foreach (RepeaterItem item in rp_Goods.Items)
            //{
            //    int ExpectAmount = DataTypePlus.requestInt(((TextBox)item.FindControl("tb_ExpectAmount")).Text);
            //    string Description = DataTypePlus.requestString(((TextBox)item.FindControl("tb_Description")).Text);
            //    if (ExpectAmount > 0)
            //    {
            //        int _id = DataTypePlus.requestInt(((TextBox)item.FindControl("tb_id")).Text);

            //        if (Orders_GoodsIDStr != "") Orders_GoodsIDStr += ",";
            //        Orders_GoodsIDStr += _id;
            //        //
            //        Model.Orders_Goods modelOrders_Goods = bllOrders_Goods.GetModel(_id);
            //        int old_ExpectAmount = modelOrders_Goods.ExpectAmount;
            //        modelOrders_Goods.ExpectAmount = ExpectAmount;
            //        modelOrders_Goods.Description = Description;
            //        modelOrders_Goods.WaitSupplierCheckNum += ExpectAmount - old_ExpectAmount;
            //        if (modelOrders_Goods.WaitSupplierCheckNum < 0) modelOrders_Goods.WaitSupplierCheckNum = 0;
            //        bllOrders_Goods.Update(modelOrders_Goods);
            //    }
            //}
            //if (Orders_GoodsIDStr == "")
            //{
            //    Maticsoft.DBUtility.DbHelperSQL.ExecuteSql("delete from Orders_Goods where  OrdersID=" + Master.id);
            //    model.State = (int)EnumHelper.OrdersState.NoGoods;
            //    bll.Update(model);
            //    BLL.User_Operate_Log.Add(CurrentStore.UserID, EnumHelper.TableName.Orders, Master.id, EnumHelper.OperateType.Update, "清空了所有选择的商品");
            //}
            //else
            //{
            //    Maticsoft.DBUtility.DbHelperSQL.ExecuteSql("delete from Orders_Goods where id not in(" + Orders_GoodsIDStr + ") and OrdersID=" + Master.id);
            //    if (model.State == (int)EnumHelper.OrdersState.NoGoods)
            //    {
            //        model.State = (int)EnumHelper.OrdersState.WaitMoney;
            //        bll.Update(model);
            //        BLL.User_Operate_Log.Add(CurrentStore.UserID, EnumHelper.TableName.Orders, Master.id, EnumHelper.OperateType.Update, "选择了商品");
            //    }
            //}

            //rp_Goods_Bing();
            #endregion

            model.State = (int)EnumHelper.OrdersState.OrderSub;
            bll.Update(model);

            #region
            int userID = Security.GetCurrentUserID();

            //ExpectPriceSum = BLL.Orders.Get_Orders_ExpectSellPriceSum(Master.id);
            //Model.Store modelStore = Security.GetCurrentStore();
            //needMoreMoney = ExpectPriceSum + 100 - (modelStore.Account - modelStore.FrozenAccount);
            //if (needMoreMoney < 0) needMoreMoney = 0;

            string content = "您" + DateTime.Now.ToString("yyyy年MM月dd日HH时mm分") + "的订单总金额为" + StringPlus.showCoin(ExpectPriceSum) + "元，预付运费100元，共计需打款金额" + StringPlus.showCoin(needMoreMoney) + "，请尽快支付以便采购，谢谢";
            BLL.Message bllmsg = new BLL.Message();
           
            bllmsg.NewMessage(0, 0, userID, content, true, true);
            #endregion 
            BLL.User_Operate_Log.Add(CurrentStore.UserID, EnumHelper.TableName.Orders, Master.id, EnumHelper.OperateType.Update, "下单了");
            Master.SubmitOK();
            
        }
        void rp_Goods_Bing()
        {
            ExpectPriceSum = BLL.Orders.Get_Orders_ExpectSellPriceSum(Master.id);
            List<BBPA.Model.V_Orders_Goods> list = bllV_Orders_Goods.GetModelList("OrdersID=" + Master.id);
            if (list.Count < 1)
            {
                Master.HideSubmit();
            }
            rp_Goods.DataSource = list;
            rp_Goods.DataBind();
            Master.ScriptManager_js("Event_Amount_change();");
            //
            tr_ExpressMoney.Visible = tr_needMoreMoney.Visible = (ExpectPriceSum > 0);
            Model.Store modelStore=Security.GetCurrentStore();
            needMoreMoney = ExpectPriceSum + 100 - (modelStore.Account - modelStore.FrozenAccount);
            if (needMoreMoney < 0 ) needMoreMoney = 0;
        }
        protected void rp_Goods_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Model.V_Orders_Goods rowData = (Model.V_Orders_Goods)e.Item.DataItem;
                TextBox tb_ExpectAmount = (TextBox)e.Item.FindControl("tb_ExpectAmount");
                tb_ExpectAmount.Text = rowData.ExpectAmount.ToString();
                ((TextBox)e.Item.FindControl("tb_id")).Text = rowData.id.ToString();
                //
                //ExpectPriceSum += rowData.ExpectAmount * DataTypePlus.requestDecimal(rowData.SellPrice);
                ((TextBox)e.Item.FindControl("tb_Description")).Text = rowData.Description.ToString();
            }
            // lb_ExpectPriceSum.Text = StringPlus.showMoney(ExpectPriceSum);
        }

        protected void btnedit_Click(object sender, EventArgs e)
        {
            string Orders_GoodsIDStr = "";
            foreach (RepeaterItem item in rp_Goods.Items)
            {
                int ExpectAmount = DataTypePlus.requestInt(((TextBox)item.FindControl("tb_ExpectAmount")).Text);
                string Description = DataTypePlus.requestString(((TextBox)item.FindControl("tb_Description")).Text);
                if (ExpectAmount > 0)
                {
                    int _id = DataTypePlus.requestInt(((TextBox)item.FindControl("tb_id")).Text);

                    if (Orders_GoodsIDStr != "") Orders_GoodsIDStr += ",";
                    Orders_GoodsIDStr += _id;
                    //
                    Model.Orders_Goods modelOrders_Goods = bllOrders_Goods.GetModel(_id);
                    int old_ExpectAmount = modelOrders_Goods.ExpectAmount;
                    modelOrders_Goods.ExpectAmount = ExpectAmount;
                    modelOrders_Goods.Description = Description;
                    modelOrders_Goods.WaitSupplierCheckNum += ExpectAmount - old_ExpectAmount;
                    if (modelOrders_Goods.WaitSupplierCheckNum < 0) modelOrders_Goods.WaitSupplierCheckNum = 0;
                    bllOrders_Goods.Update(modelOrders_Goods);
                }
            }
            if (Orders_GoodsIDStr == "")
            {
                Master.HideSubmit();
                Maticsoft.DBUtility.DbHelperSQL.ExecuteSql("delete from Orders_Goods where  OrdersID=" + Master.id);
                model.State = (int)EnumHelper.OrdersState.NoGoods;
                bll.Update(model);
                BLL.User_Operate_Log.Add(CurrentStore.UserID, EnumHelper.TableName.Orders, Master.id, EnumHelper.OperateType.Update, "清空了所有选择的商品");
            }
            else
            {
                Maticsoft.DBUtility.DbHelperSQL.ExecuteSql("delete from Orders_Goods where id not in(" + Orders_GoodsIDStr + ") and OrdersID=" + Master.id);
                if (model.State == (int)EnumHelper.OrdersState.NoGoods)
                {
                    model.State = (int)EnumHelper.OrdersState.WaitMoney;
                    bll.Update(model);
                    BLL.User_Operate_Log.Add(CurrentStore.UserID, EnumHelper.TableName.Orders, Master.id, EnumHelper.OperateType.Update, "选择了商品");
                }
            }

            rp_Goods_Bing();
        }

        protected void btnSub_Click(object sender, EventArgs e)
        {
            model.State = (int)EnumHelper.OrdersState.OrderSub;
            bll.Update(model);

            #region
            int userID = Security.GetCurrentUserID();

            //ExpectPriceSum = BLL.Orders.Get_Orders_ExpectSellPriceSum(Master.id);
            //Model.Store modelStore = Security.GetCurrentStore();
            //needMoreMoney = ExpectPriceSum + 100 - (modelStore.Account - modelStore.FrozenAccount);
            //if (needMoreMoney < 0) needMoreMoney = 0;

            string content = "您" + DateTime.Now.ToString("yyyy年MM月dd日HH时mm分") + "的订单总金额为" + StringPlus.showCoin(ExpectPriceSum) + "元，预付运费100元，共计需打款金额" + StringPlus.showCoin(needMoreMoney) + "，请尽快支付以便采购，谢谢";
            BLL.Message bllmsg = new BLL.Message();

            bllmsg.NewMessage(0, 0, userID, content, true, true);
            #endregion
            BLL.User_Operate_Log.Add(CurrentStore.UserID, EnumHelper.TableName.Orders, Master.id, EnumHelper.OperateType.Update, "下单了");
            Master.SubmitOK();
        }
    }
}